<template>
  <div>
    <el-row>
      <el-col :span="10">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="ruleForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="ruleForm.password"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :loading="loading" @click.native="submit(ruleForm)">注册</el-button>
            <el-button type="primary" :loading="loading" @click.native="login">已有帐号,去登陆</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import NProgress from 'nprogress'
import { register } from '../api/api'
export default {
  data() {
    return {
      loading: false,
      ruleForm: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 18, message: '长度在 3 到 18 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submit(ruleForm) {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$confirm('确认提交?', '提示', {
            type: 'warning'
          }).then(() => {
            NProgress.start();
            register(ruleForm).then((res) => {
              NProgress.done();
              this.loading = false;
              this.$message({
                message: res.data.message,
                type: res.data.code
              });
              location.href = '#/login'
              this.$refs['ruleForm'].resetFields();
            }, (err) => {
              this.loading = false;
              this.$message({
                message: '提交失败',
                type: 'error'
              });
            })
          }).catch(() => {
            NProgress.done();
            this.loading = false;
          });
        } else {
          console.log(valid);
        }
      });
    },
    login() {
      location.href = '#login'
    }
  }

}
</script>
